package com.josan.home;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.josan.home.util.Constance;
import com.josan.home.util.Validator;
import com.josan.home.voice.VoiceToWord;

import java.util.List;

public class MainActivity extends Activity implements SearchView.OnQueryTextListener {
    private static final String TAG = "MainActivity";
    private SearchView svSearch;
    private ListView lvAddress;
    private AddressAdapter addressAdapter;
    private List<Address> addressList;
    private Context context;
    private static Handler handler;
    private ProgressDialog pd;
    private ImageView ivVoice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main_activity);
        init();
        findViews();
        setListeners();
    }

    private void init() {
        this.context = MainActivity.this;
        addressAdapter = new AddressAdapter(MainActivity.this);
        pd = new ProgressDialog(context);
        pd.setCancelable(true);
        pd.setCanceledOnTouchOutside(false);
        // 处理消息
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                try {
                    switch (msg.what) {
                        case Constance.INIT_DATA_FINISHED: // 得到数据完成
                        case Constance.SHOW_DIALOG: // 显示对话框
                            if (pd != null) {
                                pd.setMessage("首次初始化数据，莫动它，完成会自动关闭的...");
                                pd.show();
                            }
                            break;

                        case Constance.CLOSE_DIALOG: // 关闭对话框
                            if (pd != null && pd.isShowing()) {
                                pd.dismiss();
                            }
                            break;
                        case Constance.VOICE_DATA_FINISHED: // 语音识别
                            String text = (String) msg.obj;
                            svSearch.setQuery(text, true);
                            break;


                        default:
                            break;
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                    Log.v(TAG, "出错了--》" + e.getMessage());
                }

            }

        };
    }

    public static Handler getHander() {
        return handler;
    }

    /**
     * 找到控件
     */
    @SuppressLint("NewApi")
    private void findViews() {
        svSearch = (SearchView) this.findViewById(R.id.search_view);
        svSearch.setSubmitButtonEnabled(true);
        // 为改SerchView组件设置事件监听器
        svSearch.setOnQueryTextListener(this);
        lvAddress = (ListView) this.findViewById(R.id.lv_address);
        lvAddress.setAdapter(addressAdapter);
        ivVoice = (ImageView) this.findViewById(R.id.iv_voice);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        ivVoice.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //为什么不能用自己的
                VoiceToWord voice = new VoiceToWord(MainActivity.this, "57fc8a6a");
                voice.GetWordFromVoice();
            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // getAddressData(null);
    }


    /**
     * 数据适配器类，给Listview填充数据
     */
    public class AddressAdapter extends BaseAdapter {
        private List<Address> addressList;
        private LayoutInflater myInflater; // LayoutInfalter对象用来导入布局

        public AddressAdapter(Context context) {
            this.myInflater = LayoutInflater.from(context);
        }

        public void setData(List<Address> addressList) {
            this.addressList = addressList;
        }

        public int getCount() {
            if (this.addressList != null) {
                return this.addressList.size();
            }
            return 0;
        }

        public Object getItem(int paramInt) {
            return paramInt;
        }

        public long getItemId(int paramInt) {
            return paramInt;
        }

        // 绘制ListItem的方法
        public View getView(final int position, View paramView,
                            ViewGroup paramViewGroup) {
            View view = paramView;
            ViewHolder holder = null;
            if (paramView == null) {
                // 加载ListItem布局文件
                view = myInflater.inflate(R.layout.address_item, null);
                holder = new ViewHolder();
                // 得到各个控件的对象
                holder.tvFilter = (TextView) view.findViewById(R.id.tv_filter);
                // 绑定ViewHolder对象到view上
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag(); // 取出ViewHolder对象
            }
            // 得到当前ListItem需要填充的图书数据
            return view;

        }

    }

    /**
     * ListItem界面控件的持有类
     */
    class ViewHolder {
        TextView tvFilter;
        TextView tvCity;
        TextView tvDistrict;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        closeKeyBoard(context, svSearch);
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        // TODO Auto-generated method stub
        if (Validator.isEffective(newText)) {
            // getAddressData(newText);
        } else {
            addressAdapter.setData(null);
            addressAdapter.notifyDataSetChanged();
        }

        return false;
    }

    public void closeKeyBoard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // 强制隐藏
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}